#include "app_mqtt.h"
#include "log/log.h"
#include <MQTTClient.h>
static MQTTClient_message pubmsg = MQTTClient_message_initializer;
static MQTTClient client;
static MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;

static int (*recv_callback)(char *, int);

// 发送消息的回调函数
static void delivered(void *context, MQTTClient_deliveryToken dt)
{
    log_debug("消息发送完成");
}

// 收到消息的回调函数
static int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{
    int result = 0; // 定义一 个代表消息未正确处理的值
    // 调用recv_callback处理消息
    if(recv_callback)
    {
        result = recv_callback(message->payload, message->payloadlen)==0 ? 1 : 0;
    }

    // 释放消息资源
    MQTTClient_freeMessage(&message);
    MQTTClient_free(topicName);

    // 返回消息处理结果
    return result; // 1: 消息处理成功， 0: 消息处理失败
}

// 连接断开的回调函数
static void connlost(void *context, char *cause)
{
    log_error("连接断开， 原因: %s", cause);
}


int app_mqtt_init()
{

    int result;

    // 创建客户端
    if ((result =MQTTClient_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL)) != MQTTCLIENT_SUCCESS)
    {
        log_error("MQTTClient_create failed: %d", result);
        return -1;
    }
    // 设置回调函数
    if ((result =MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered)) != MQTTCLIENT_SUCCESS)
    {
        log_error("MQTTClient_setCallbacks failed: %d", result);
        MQTTClient_destroy(&client);
        return -1;
    }

    // 连接服务器
    if ((result =MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
    {
        log_error("MQTTClient_connect failed: %d", result);
        MQTTClient_destroy(&client);
        return -1;
    }

    // 订阅主题
    if ((result =MQTTClient_subscribe(client, TOPIC_PULL, QOS)) != MQTTCLIENT_SUCCESS)
    {
        log_error("MQTTClient_subscribe failed: %d", result);
        app_mqtt_close();
        return -1;
    }

    return 0;
}


int app_mqtt_send(char *data, int len)
{
    // 设置消息内容
    pubmsg.payload = data;
    pubmsg.payloadlen = len;
    pubmsg.qos = QOS;

    if (MQTTClient_publishMessage(client, TOPIC_PUSH, &pubmsg, NULL) != MQTTCLIENT_SUCCESS)
    {
        log_error("MQTTClient_publishMessage failed");
        return -1;
    }
    return 0;
}


void app_mqtt_registRecvCallback(int (*callback)(char *, int))
{
    recv_callback = callback;
}

void app_mqtt_close()
{
    MQTTClient_disconnect(client, TIMEOUT);
    MQTTClient_destroy(&client);
}